package com.psbc.online_xdclass.service.impl;

import com.psbc.online_xdclass.model.entity.User;
import com.psbc.online_xdclass.mapper.UserMapper;
import com.psbc.online_xdclass.model.request.LoginRequest;
import com.psbc.online_xdclass.service.UserService;
import com.psbc.online_xdclass.utils.CommonUtils;
import com.psbc.online_xdclass.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 添加用户
     * @param userInfo
     * @return
     */
    @Override
    public int save(Map<String, String> userInfo) {
        User user = parseUser(userInfo);
        if (user != null){
           return userMapper.save(user);
        }else {
            return -1;
        }
    }

    /**
     * 用户登录
     * @param  phone,pwd
     * @return
     */
    @Override
    public String findByPhoneAndPwd(String phone,String pwd) {
        User user = userMapper.findByPhoneAndPwd(phone,CommonUtils.MD5(pwd));
        if (user == null){
            return null;
        }else {
            String token = JwtUtils.geneJsonWebToken(user);
            return token;
        }
    }

    /**
     * 根据用户Id查询用户信息
     * @param userId
     * @return
     */
    @Override
    public User findUserById(Integer userId) {
        User user = userMapper.findUserById(userId);
        return user;
    }

    /**
     * 用户解析
     * @param userInfo
     * @return
     */
    private User parseUser(Map<String, String> userInfo) {
        if (userInfo.containsKey("name") && userInfo.containsKey("pwd") && userInfo.containsKey("phone")){
            User user = new User();
            user.setName(userInfo.get("name"));
            user.setPhone(userInfo.get("phone"));
            String pwd = userInfo.get("phone");
            user.setPwd(CommonUtils.MD5(pwd));
            user.setCreateTime(new Date());
            user.setHeadImg(getRandomImg());
            return user;
        }else {
            return null;
        }
    }
    //放在CDN上的头像信息，放在一个字符串数组里
    private static final String [] headImg = {
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/12.jpeg",
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/11.jpeg",
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/13.jpeg",
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/14.jpeg",
            "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/15.jpeg"
    };
    //生成随机头像
    private String getRandomImg(){
        int size = headImg.length;
        Random random = new Random();
        int index = random.nextInt(size);
        return headImg[index];
    }

}
